package com.irdstudio.apicenter.core.utils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

/**
 * 处理信贷系统中字符串或公式工具类
 * 
 * @Classname com.yucheng.cmis.pub.util.StringUtil.java
 * @author wqgang
 * @Since 2008-9-7 上午10:16:51
 * @Copyright yuchengtech
 * @version 1.0
 */
public class StringUtil {
	private static final StringUtil instance = new StringUtil();

	public StringUtil() {
	}

	public static final StringUtil getInstance() {
		return instance;
	}

	/**
	 * 根据输入的用户号来获取该用户角色号
	 */
	public static List selectRole(Connection connection, String user_id)
			throws Exception {
		List list = new ArrayList();
		Statement st = null;
		ResultSet rs = null;
		try {
			st = connection.createStatement();
			String sql = "select roleno from s_roleuser where actorno='"
					+ user_id + "'";
			rs = st.executeQuery(sql);
			while (rs.next()) {
				String roleno = rs.getString("roleno");
				list.add(roleno);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;

	}

	/**
	 * 本方法的主要功能是在一个字符串的每个大写字母前面加一个_ ，字符串的首字母除外 然后把整个串以小写输出 例如：cusId-->cus_id
	 * 
	 * @param str
	 *            传入的字符串
	 * @return 处理后的字符串
	 */

	public static String AddUnderlineByUppercase(String str) {
		// int count=0;
		String rv = "";

		if (null == str || str.trim().length() == 0) {
			return str;
		}

		StringBuffer tmpStr = new StringBuffer("");
		for (int i = 0; i < str.length(); i++) {
			if (Character.isUpperCase(str.charAt(i))) {
				tmpStr.append("_").append(Character.valueOf(str.charAt(i)));
				// count ++;
			} else {
				tmpStr.append(Character.valueOf(str.charAt(i)));
			}
		}

		rv = tmpStr.toString().toLowerCase();
		if (rv.substring(0, 1).equals("_")) {
			rv = rv.substring(1);
		}
		return rv;
	}

	/***
	 * 将字符串转换为驼峰命名 如t_able_name_a -> TableNameA
	 * 
	 * @param str
	 * @return
	 */
	public static String transToCamelStyle(String str) {
		if ("".equals(str))
			return "";
		str = str.substring(0, 1).toUpperCase()
				+ str.substring(1, str.length()).toLowerCase();// 首字母大写,其余小写
		StringBuffer tmpStr = new StringBuffer("");
		for (int i = 0; i < str.length(); i++) {
			if ("_".equals(str.substring(i, i + 1))) {// 如果本字符是“_”,将下一字符(如果有)转为大写
				if (i != str.length() - 1) {
					str = str.substring(0, i + 1)
							+ str.substring(i + 1, i + 2).toUpperCase()
							+ str.substring(i + 2, str.length());
				}
			} else {
				tmpStr.append(str.charAt(i));// tmpStr 添加本字符
			}

		}

		return tmpStr.toString();
	}

	public static String AddUnderlineByUppercase2(String str) {

		// 创建一个数组列表，用来存储大写字母的位置

		// ArrayList<Integer> al = new ArrayList<Integer>();
		// int count = 0;
		// for(int j=1; j<str.length(); j++){
		// if(Character.isUpperCase(str.charAt(j))){
		// al.add(j);
		// count ++;
		// }
		ArrayList<Integer> al = new ArrayList<Integer>();
		int count = 0;
		for (int j = 0; j < str.length(); j++) {
			if (Character.isUpperCase(str.charAt(j))) {
				al.add(j);
				count++;
			}
			// if(NewStringUtils.isNumeric((Character.toString(str.charAt(j))))){
			// al.add(j);
			// count ++;
			// }
		}
		if (count == 0) {
			return str;
		}
		StringBuffer tmpStr = new StringBuffer("");

		// 根据大小字母的位置在其前面加上 _

		for (int x = 0; x < al.size(); x++) {
			if ((x == 0) && (x == al.size() - 1)) {
				if (str.length() == 1) {
					tmpStr.append(str);
				} else {
					tmpStr.append(str.substring(0, al.get(x))).append("_")
							.append(str.substring(al.get(x), str.length()));
				}

			} else if ((x == 0) && (x != al.size() - 1)) {
				tmpStr.append(str.substring(0, al.get(x))).append("_");
			} else if ((x != 0) && (x == al.size() - 1)) {
				if (al.get(x) == str.length()) {
					tmpStr.append(str.substring(al.get(x - 1), al.get(x)));
				} else {
					tmpStr.append(str.substring(al.get(x - 1), al.get(x)))
							.append("_").append(
									str.substring(al.get(x), str.length()));
				}
			} else {
				tmpStr.append(str.substring(al.get(x - 1), al.get(x))).append(
						"_");
			}
		}
		// 转换成小写返回
		String rv = tmpStr.toString().toLowerCase();
		if (rv.substring(0, 1).equals("_")) {
			rv = rv.substring(1);
		}
		return rv;
	}

	/**
	 * 改变字符串中的某一位的字符值
	 * 
	 * @param source
	 *            需要改变的字符串
	 * @param position
	 *            位置
	 * @param changeChar
	 *            改变后的字符
	 * @return 输入 ("abc",2,'e') 输出"abe"
	 */
	public static String changeCharInString(String source, int position,
			char changeChar) throws Exception {
		if (source == null) {
			return null;
		}
		char[] sourceList = source.toCharArray();

		if (source.length() <= position) {
			throw new Exception("输入参数不合法");
		}
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < sourceList.length; i++) {
			if (i == position) {
				sb.append(changeChar);
			} else {
				sb.append(sourceList[i]);
			}
		}

		return sb.toString();
	}

	/**
	 * 加密 *
	 * 
	 * @param source
	 *            byte[]
	 * @return byte[]
	 */
	public static byte[] addKey(byte[] source) {
		byte[] reByte = new byte[source.length];
		String key = "dlvanda";
		byte[] keyByte = key.getBytes();
		for (int i = 0; i < source.length; i++) {
			int j = i % keyByte.length;
			reByte[i] = (byte) (source[i] + keyByte[j]);
		}
		return reByte;
	}

	/**
	 * 解密 *
	 * 
	 * @param source
	 *            byte[]
	 * @return byte[]
	 */
	public static byte[] desKey(byte[] source) {
		byte[] reByte = new byte[source.length];
		String key = "dlvanda";
		byte[] keyByte = key.getBytes();
		for (int i = 0; i < source.length; i++) {
			int j = i % keyByte.length;
			reByte[i] = (byte) (source[i] - keyByte[j]);
		}
		return reByte;
	}

	/**
	 * 加密 *
	 * 
	 * @param source
	 *            String
	 * @return String
	 */
	// public String addKey(String source) {
	// Descrypt des = new Descrypt();
	// return des.descrypt(source,"dlvanda");
	// }

	/**
	 * 返回两位数据字串 *
	 * 
	 * @param sz
	 *            int
	 * @return String
	 */
	public static String bZero(int sz) {
		return (sz < 10 ? ("0" + String.valueOf(sz)) : String.valueOf(sz));
	}

	/**
	 * 字符串("|")到数组 *
	 * 
	 * @param string
	 *            String
	 * @return String[]
	 */
	public static String[] strToArray(String string) {
		String tmpString;
		String[] returnArray = null;
		if (string == null || string.equalsIgnoreCase("")) {
			returnArray = new String[1];
			returnArray[0] = "";
		} else {
			int j = 0, jsInt = 0;
			for (int i = 0; i < string.length(); i++) {
				if (string.charAt(i) == '|') {
					j++;
				}
			}
			if (j == 0) {
				returnArray = new String[1];
				returnArray[0] = string;
			} else {
				returnArray = new String[j];
				j = 0;
				for (int i = 0; i < string.length(); i++) {
					if (string.charAt(i) == '|') {
						if (j == i) {
							tmpString = " ";
						} else {
							tmpString = string.substring(j, i).trim();
						}
						j = i + 1;
						returnArray[jsInt] = tmpString;
						jsInt += 1;
					}
				}
			}
		}
		return returnArray;
	}

	/**
	 * 字符串到数组 *
	 * 
	 * @param string
	 *            String
	 * @param separator
	 *            char
	 * @return String[]
	 */
	public static String[] strToArray(String string, char separator) {
		String[] returnArray;
		if (string == null || string.equalsIgnoreCase("")) {
			returnArray = new String[1];
			returnArray[0] = "";
		} else {
			int j = 0, lastpos = 0;
			ArrayList pos = new ArrayList();
			pos.add(String.valueOf(-1));
			for (int i = 0; i < string.length(); i++) {
				if (string.charAt(i) == separator) {
					j++;
					lastpos = i;
					pos.add(String.valueOf(i));
				}
			}
			if (lastpos != string.length()) {
				j++;
				pos.add(String.valueOf(string.length()));
			}

			int[] ps = new int[pos.size()];
			for (int i = 0; i < ps.length; i++) {
				ps[i] = Integer.parseInt(String.valueOf(pos.get(i)));
			}
			returnArray = new String[ps.length - 1];
			for (int i = 0; i < returnArray.length; i++) {
				returnArray[i] = string.substring(ps[i] + 1, ps[i + 1]).trim();
			}

		}
		return returnArray;
	}

	/**
	 * 数组到字串,用"|"隔开 *
	 * 
	 * @param strArray
	 *            String[]
	 * @return String
	 */
	public static String arrayToStr(String strArray[]) {
		String reStr = "";
		if (strArray != null) {
			for (int i = 0; i < strArray.length; i++) {
				if (strArray[i] != null) {
					reStr = reStr + strArray[i].trim() + "|";
				} else {
					reStr = reStr + "|";
				}
			}
		}
		return reStr;
	}

	/**
	 * 得到两个字符间的字符串 *
	 * 
	 * @param string
	 *            String
	 * @param leftFlag
	 *            char
	 * @param rightFlag
	 *            char
	 * @return String
	 */
	public static String getParamString(String string, char leftFlag,
			char rightFlag) {
		String param = "";

		while (string.indexOf(rightFlag) < string.indexOf(leftFlag))
			string = string.substring(string.indexOf(rightFlag) + 1);

		if (string.indexOf(leftFlag) >= 0 && string.indexOf(rightFlag) >= 0) {
			int pos1 = string.indexOf(leftFlag);
			int pos2 = string.indexOf(rightFlag);
			param = string.substring(pos1 + 1, pos2);
		}

		return param;
	}

	/**
	 * 得到两个相同字符间的字符串 *
	 * 
	 * @param string
	 *            String
	 * @param leftFlag
	 *            char
	 * @param rightFlag
	 *            char
	 * @return String
	 */
	public static String getParam(String string, char flag) {
		if (string == null || string.equalsIgnoreCase(""))
			return "";

		String param = "";
		int pos1 = string.indexOf(flag);
		int pos2 = 0;
		if (pos1 >= 0) {
			pos2 = string.indexOf(flag, pos1 + 1);

			if (pos2 > 0) {
				param = string.substring(pos1 + 1, pos2);
			}
		}
		return param;
	}

	/**
	 * 得到一个字符串中所有两个字符间的字符串 *
	 * 
	 * @param string
	 *            String
	 * @param leftFlag
	 *            char
	 * @param rightFlag
	 *            char
	 * @return List
	 */
	public static List getParamList(String string, char leftFlag, char rightFlag) {
		String param = "";
		List<String> lt = new ArrayList<String>();
		while (string.indexOf(leftFlag) != -1) {
			while (string.indexOf(rightFlag) < string.indexOf(leftFlag))
				string = string.substring(string.indexOf(rightFlag) + 1);

			if (string.indexOf(leftFlag) >= 0 && string.indexOf(rightFlag) >= 0) {
				int pos1 = string.indexOf(leftFlag);
				int pos2 = string.indexOf(rightFlag);
				param = string.substring(pos1 + 1, pos2);
				string = string.substring(pos2 + 1);
				lt.add(param);
			}

		}
		return lt;
	}

	/**
	 * 目标字符串编码转化
	 * 
	 * @param targetStr
	 *            目标字符串
	 * @param localcode
	 *            目标字符串编码
	 * @param targetCode
	 *            需要转化字符串编码
	 * @return
	 */
	public static String getStrEncode(String targetStr, String localcode,
			String targetCode) {
		try {
			byte[] bytes = targetStr.getBytes(localcode);
			targetStr = new String(bytes, targetCode);
		} catch (Exception e) {
			// e.printStackTrace();
		}
		return targetStr;

	}

	/**
	 * 用str2 替换 str与str1 间字串 *
	 * 
	 * @param str
	 *            String
	 * @param str1
	 *            String
	 * @param str2
	 *            String
	 * @return String
	 */
	public static String replace(String str, String str1, String str2) {
		for (int pos = str.indexOf(str1); pos >= 0; pos = str.indexOf(str1))
			str = new String(new StringBuffer(str.substring(0, pos)).append(
					str2).append(str.substring(str1.length() + pos)));

		return str;
	}

	/**
	 * 根据算术式String求出结果
	 * 
	 * @param str
	 *            String
	 * @return String result
	 */

	/**
	 * 得到10位随机码
	 * 
	 * @return
	 */
	public static String getRandomId() {
		String str = "";
		int[] t = new int[10];
		Random rand = new Random();
		for (int i = 0; i < t.length; i++) {
			t[i] = rand.nextInt(10);
		}
		for (int i = 0; i < t.length; i++) {
			str += t[i];
		}
		return str;
	}

	/**
	 * @param stringList
	 *            字符串集合
	 * @return 返回SQL语句中in的部分 如: '0001','0002','0003'
	 */
	public static String listToString(List<String> stringList) {
		if (stringList == null || stringList.isEmpty()) {
			return null;
		} else {
			StringBuffer sb = new StringBuffer();
			for (Iterator<String> iterator = stringList.iterator(); iterator
					.hasNext();) {
				String string = iterator.next();
				sb.append(",'").append(string).append("'");
			}
			return sb.toString().substring(1);
		}
	}

	/**
	 * @param SQL
	 *            模糊查询
	 * @return
	 */
	public static String transConditionStr(String conditionStr, String field) {

		String str = " " + field + " ";
		String str2 = "(" + field + " ";
		int j = conditionStr.indexOf(str);
		if (j != -1) {
			conditionStr = conditionStr.replace(str + "= '", str + "like '%");
			str = str + "like '%";
			int otherStart = conditionStr.indexOf(str) + str.length();
			int oIndex = conditionStr.indexOf("'", otherStart);
			conditionStr = conditionStr.substring(0, oIndex) + "%'"
					+ conditionStr.substring(oIndex + 1);
			// conditionStr = conditionStr.replace(conditionStr.substring(j,
			// oIndex+1),conditionStr.substring(j,oIndex)+"%'");
		}
		if (conditionStr.indexOf(str2) != -1) {
			conditionStr = conditionStr.replace(str2 + "= '", str2 + "like '%");
			str2 = str2 + "like '%";
			int otherStart = conditionStr.indexOf(str2) + str2.length();
			int oIndex = conditionStr.indexOf("'", otherStart);
			conditionStr = conditionStr.substring(0, oIndex) + "%'"
					+ conditionStr.substring(oIndex + 1);
			// conditionStr = conditionStr.replace(conditionStr.substring(j,
			// oIndex+1),conditionStr.substring(j,oIndex)+"%'");
		}

		return conditionStr;
	}

	/**
	 * 得到字符串中的所有数字
	 * 
	 * @param str
	 * @return
	 */
	public static String getStringNumber(String str) {
		String regEx = "[^0-9]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.replaceAll("").trim();
	}

	/**
	 * 数字金额大写转换，思想先写个完整的然后将如零拾替换成零 要用到正则表达式
	 */
	public static String digitUppercase(double n) {
		String fraction[] = { "角", "分" };
		String digit[] = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
		String unit[][] = { { "元", "万", "亿" }, { "", "拾", "佰", "仟" } };

		String head = n < 0 ? "负" : "";
		n = Math.abs(n);

		String s = "";
		for (int i = 0; i < fraction.length; i++) {
			s += (digit[(int) (Math.floor(n * 10 * Math.pow(10, i)) % 10)] + fraction[i])
					.replaceAll("(零.)+", "");
		}
		if (s.length() < 1) {
			s = "整";
		}
		int integerPart = (int) Math.floor(n);

		for (int i = 0; i < unit[0].length && integerPart > 0; i++) {
			String p = "";
			for (int j = 0; j < unit[1].length && n > 0; j++) {
				p = digit[integerPart % 10] + unit[1][j] + p;
				integerPart = integerPart / 10;
			}
			s = p.replaceAll("(零.)*零$", "").replaceAll("^$", "零") + unit[0][i]
					+ s;
		}
		return head
				+ s.replaceAll("(零.)*零元", "元").replaceFirst("(零.)+", "")
						.replaceAll("(零.)+", "零").replaceAll("^整$", "零元整");
	}

	/**
	 * 
	 * 方法描述 将字符串转化为unicode编码
	 * 
	 * @param 源字符串
	 * @return
	 */
	public static String gbEncoding(final String gbString) {
		if (StringUtils.isEmpty(gbString)) {
			return "";
		}
		char[] utfBytes = gbString.toCharArray();
		String unicodeBytes = "";
		for (int byteIndex = 0; byteIndex < utfBytes.length; byteIndex++) {
			String hexB = Integer.toHexString(utfBytes[byteIndex]);
			if (hexB.length() <= 2) {
				hexB = "00" + hexB;
			}
			unicodeBytes = unicodeBytes + "\\u" + hexB;
		}
		// System.out.println("unicodeBytes is: " + unicodeBytes);
		return unicodeBytes;
	}

	/**
	 * 
	 * 方法描述 将unicode编码转化为中文字符串
	 * 
	 * @param 源字符串
	 * @return
	 */
	public static String decodeUnicode(final String dataStr) {
		if (StringUtils.isEmpty(dataStr)) {
			return "";
		}
		int start = 0;
		int end = 0;
		final StringBuffer buffer = new StringBuffer();
		while (start > -1) {
			end = dataStr.indexOf("\\u", start + 2);
			String charStr = "";
			if (end == -1) {
				charStr = dataStr.substring(start + 2, dataStr.length());
			} else {
				charStr = dataStr.substring(start + 2, end);
			}
			char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。
			buffer.append(new Character(letter).toString());
			start = end;
		}
		return buffer.toString();
	}
}
